package com.sim.simserial.ui

import android.app.AlertDialog
import android.util.Log
import androidx.fragment.app.viewModels
import com.drake.brv.utils.grid
import com.drake.brv.utils.models
import com.drake.brv.utils.setup
import com.drake.channel.receiveEvent
import com.infinit.selfhelp.common.base.ViewBindingFragment
import com.sim.serialport.library.seria.SerialManager
import com.sim.simserial.R
import com.sim.simserial.databinding.FragmentFunctionsBinding
import com.sim.simserial.databinding.ItemFunctionBinding
import com.sim.simserial.navigation.MainNavigator
import com.sim.simserial.ui.RequestAndResponseFragment.Companion.GET_LAST_APPROVED_TRANSACTION
import com.sim.simserial.ui.RequestAndResponseFragment.Companion.LOGON
import com.sim.simserial.ui.RequestAndResponseFragment.Companion.Request_terminal_status
import com.sim.simserial.ui.RequestAndResponseFragment.Companion.Settlement
import com.sim.simserial.ui.RequestAndResponseFragment.Companion.TMS
import com.sim.simserial.utils.SerialDataBuilder
import com.sim.simserial.viewmodel.SimViewModel
import com.sim.storage.FunctionBean
import com.sim.storage.enums.FunctionCode
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import javax.inject.Inject

@AndroidEntryPoint
class AdminFragment : ViewBindingFragment<FragmentFunctionsBinding>(R.layout.fragment_functions) {

    private val adminViewModel by viewModels<SimViewModel>()

    @Inject
    lateinit var serialManager: SerialManager

    @Inject
    lateinit var homeNavigator: MainNavigator

    override fun initView() {
        super.initView()
        adminViewModel.getData()
        mBinding.rvFun.grid(2).setup { adapter ->
            addType<FunctionBean>(R.layout.item_function)
            onBind {
                getBinding<ItemFunctionBinding>().tvFun.setOnClickListener {
                    val functionBean = getModel<FunctionBean>()
                    when (functionBean.funcName) {
                        Request_terminal_status -> {
//                            showLoadingDialogWithCancel(requireContext(),true)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildRequestTerminalStatus())
                        }

                        LOGON -> {
//                            showLoadingDialogWithCancel(requireContext(),true)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildLogonRequest())
                        }

                        Settlement -> {
                            // 先结算NETS，间隔20s, 再结算Credit Card,再间隔20s, 更新TMS
//                            showLoadingDialogWithCancel(requireContext(),true)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildNETSSettlement())
                        }

                        TMS -> {
//                            showLoadingDialogWithCancel(requireContext(),true)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildTMSRequest())
                        }

                        GET_LAST_APPROVED_TRANSACTION -> {
//                            showLoadingDialogWithCancel(requireContext(),true)
                            val buildLastApprovedRequest = SerialDataBuilder.buildLastApprovedRequest()
                            adminViewModel.sendDataWithACK2(buildLastApprovedRequest)
                        }

                    }
                }
            }
        }.models = listOf()

    }

    override fun onEvent() {
    }

    override fun observe() {
        super.observe()
        receiveEvent<SimViewModel.FunctionEvent> {
            mBinding.rvFun.models = it.list
        }
        receiveEvent<SimViewModel.XSimEvent> {
            if (it !is SimViewModel.LogEvent) {
                hideLoadingDialog()
            }

            when (it) {
                is SimViewModel.ResponseEvent -> {
                    when (it.response.messageHeader.functionCode) {
                        FunctionCode.CODE_SETTLEMENT_NETS_81.code -> {
                            delay(20000)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildCreditCardSettlement())
                        }

                        FunctionCode.CODE_SETTLEMENT_CREDIT_CARD_I5.code -> {
                            delay(20000)
                            adminViewModel.sendDataWithACK2(SerialDataBuilder.buildTMSRequest())
                            hideLoadingDialog()
                        }

                        else -> {

                        }
                    }
                    mBinding.logView.addItems("response 解析：  ${it.response.toString()}")
                }

                is SimViewModel.LogEvent -> {
                    Log.d("log--", it.log)
                    mBinding.logView.addItems("${if (it.isPos) "pos:" else "terminal:"} ${it.log}")
                }

                is SimViewModel.ErrorReplyEvent -> {
                    val b = AlertDialog.Builder(requireContext())
                    b.setTitle("Error")
                    b.setMessage(it.error.errorTypeName)
                    b.setPositiveButton("OK") { dialog, which -> }
                    b.show()
                }

                is SimViewModel.WrongLRCEvent -> {
                    val b = AlertDialog.Builder(requireContext())
                    b.setTitle("Error")
                    b.setMessage(it.error)
                    b.setPositiveButton("OK") { dialog, which -> }
                    b.show()
                }
            }
        }
    }
}